package gui;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTextField;
import javax.swing.JCheckBox;

import entities.Calendar;
import entities.Category;
import exceptions.IllegalAppointmentException;
import fachlogik.Administration;
import fachlogik.CategoriesCellRenderer;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class CategoryWindow extends JFrame {

	private JPanel contentPane;
	private JTextField tf_begin;
	private JTextField tf_end;
	private JTextField tf_name;
	private JComboBox cb_categories;
	private JCheckBox chckbxNewCheckBox;

	private Administration instance;
	private MainWindow mw;
	private Calendar selectedCalendar;
	private Category selectedCategory;
	private SimpleDateFormat sf;
	private CalendarWindow cw;

	private DefaultComboBoxModel<Category> dcm;

	/**
	 * Launch the application.
	 */
	// public static void main(String[] args) {
	// EventQueue.invokeLater(new Runnable() {
	// public void run() {
	// try {
	// CategoryWindow frame = new CategoryWindow();
	// frame.setVisible(true);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// });
	// }

	/**
	 * Create the frame.
	 */
	public CategoryWindow(Calendar c, final CalendarWindow cw) {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				cw.setCatWindow(null);
			}
		});
		// this.mw = mw;

		this.cw = cw;
		dcm = new DefaultComboBoxModel<>();
		instance = Administration.getInstance();
		selectedCalendar = c;
		sf = new SimpleDateFormat("HH:mm");
		sf.setLenient(false);
		setLocationRelativeTo(null);
		setResizable(false);
		setVisible(true);

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setTitle("Categories");
		setBounds(100, 100, 242, 362);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblNewLabel = new JLabel("Choose a category:");
		lblNewLabel.setBounds(12, 15, 163, 15);
		contentPane.add(lblNewLabel);

		JLabel lblNewLabel_0 = new JLabel("Name:");
		lblNewLabel_0.setBounds(12, 90, 70, 15);
		contentPane.add(lblNewLabel_0);

		JLabel lblNewLabel_1 = new JLabel("Begin:");
		lblNewLabel_1.setBounds(12, 120, 70, 15);
		contentPane.add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("End:");
		lblNewLabel_2.setBounds(12, 150, 70, 15);
		contentPane.add(lblNewLabel_2);

		JLabel lblNewLabel_3 = new JLabel("Weekend allowed:");
		lblNewLabel_3.setBounds(12, 180, 141, 15);
		contentPane.add(lblNewLabel_3);

		JButton btn_saveCategory = new JButton("Save Category");
		btn_saveCategory.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String name = tf_name.getText();
				String begin = tf_begin.getText();
				String end = tf_end.getText();
				if (!name.equals("") && !begin.equals("") && !end.equals("")) {
					try {
						selectedCategory.setName(name);
						selectedCategory.setAnfangszeit(sf.parse(begin));
						selectedCategory.setEndzeit(sf.parse(end));
						selectedCategory.setWochenendeErlaubt(chckbxNewCheckBox
								.isSelected());
						instance.editCategory(selectedCategory);
						cw.setCatWindow(null);
						if(cw.getAd() != null)
						{
							cw.getAd().cbAktualisieren();
							cw.getAd().ausgewaehlteCategory(selectedCategory);
						}
						dispose();
					} catch (ParseException e1) {
						JOptionPane
								.showMessageDialog(null,
										"Please enter the date in the following format: hh:mm");
					}
				} else
					JOptionPane.showMessageDialog(null,
							"Please complete all fields!");
			}
		});
		btn_saveCategory.setBounds(10, 206, 206, 25);
		contentPane.add(btn_saveCategory);

		JButton btn_saveAsNewCategory = new JButton("Save As New Category");
		btn_saveAsNewCategory.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (selectedCalendar != null) {
					String name = tf_name.getText();
					String begin = tf_begin.getText();
					String end = tf_end.getText();
					if (!name.equals("") && !begin.equals("")
							&& !end.equals("")) {
						try {
							Category c = new Category();
							c.setName(name);
							c.setAnfangszeit(sf.parse(begin));
							c.setEndzeit(sf.parse(end));
							c.setCalendar(selectedCalendar);
							c.setWochenendeErlaubt(chckbxNewCheckBox
									.isSelected());
							instance.addCategory(c);
							cw.setCatWindow(null);
							if(cw.getAd() != null)
							{
								cw.getAd().cbAktualisieren();
								cw.getAd().ausgewaehlteCategory(c);
							}
							dispose();
						} catch (ParseException e1) {
							JOptionPane
									.showMessageDialog(null,
											"Please enter the date in the following format: hh:mm");
						}
					} else
						JOptionPane.showMessageDialog(null,
								"Please complete all fields!");
				}
				else
				{
					JOptionPane.showMessageDialog(null, "Please choose a calendar first");
					cw.setCatWindow(null);
					dispose();
				}
			}
		});
		btn_saveAsNewCategory.setBounds(10, 234, 206, 25);
		contentPane.add(btn_saveAsNewCategory);

		JButton btn_cancel = new JButton("Cancel");
		btn_cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cw.setCatWindow(null);
				dispose();
			}
		});
		btn_cancel.setBounds(10, 288, 206, 25);
		contentPane.add(btn_cancel);

		tf_begin = new JTextField();
		tf_begin.setBounds(100, 120, 125, 19);
		contentPane.add(tf_begin);
		tf_begin.setColumns(10);

		tf_end = new JTextField();
		tf_end.setBounds(100, 150, 125, 19);
		contentPane.add(tf_end);
		tf_end.setColumns(10);

		tf_name = new JTextField();
		tf_name.setBounds(100, 90, 125, 19);
		contentPane.add(tf_name);
		tf_name.setColumns(10);

		chckbxNewCheckBox = new JCheckBox("");
		chckbxNewCheckBox.setBounds(175, 176, 129, 23);
		contentPane.add(chckbxNewCheckBox);

		cbAktualisieren();
		cb_categories = new JComboBox(dcm);
		cb_categories.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				selectedCategory = (Category) cb_categories.getSelectedItem();
				tfBefuellen();
			}
		});
		cb_categories.setRenderer(new CategoriesCellRenderer());
		cb_categories.setBounds(10, 41, 213, 24);
		contentPane.add(cb_categories);
		if (dcm.getElementAt(0) != null) {
			selectedCategory = (Category) dcm.getElementAt(0);
			tfBefuellen();
		}

		JButton btnDeleteCategory = new JButton("Delete Category");
		btnDeleteCategory.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (selectedCategory != null) {
					try {
						instance.removeCategory(selectedCategory);
						cbAktualisieren();
						cw.setCatWindow(null);
						if(cw.getAd() != null)
							cw.getAd().cbAktualisieren();
						dispose();
					} catch (IllegalAppointmentException e1) {
						AppointmentDialog AppDia = new AppointmentDialog(e1
								.getWrongApp(), null);
						JOptionPane.showMessageDialog(null, "The Appointment "
								+ e1.getWrongApp().getName()
								+ "starts after the end of the Appointment", e1
								.getWrongApp().getName()
								+ "hat ein Fehler verursacht", 0);
						e1.printStackTrace();
					}
				}
			}
		});
		btnDeleteCategory.setBounds(10, 262, 206, 23);
		contentPane.add(btnDeleteCategory);

		selectedCategory = (Category) cb_categories.getSelectedItem();

	}

	public void cbAktualisieren() {
		dcm.removeAllElements();
		for (Category cat : instance.getCalendarCategories(selectedCalendar)) {
			dcm.addElement(cat);
		}
	}

	public void tfBefuellen() {
		if (selectedCategory != null) {
			if (!selectedCategory.getName().equals("")) {
				tf_name.setText(selectedCategory.getName());
			}
			if (selectedCategory.getAnfangszeit() != null)
				tf_begin.setText(sf.format(selectedCategory.getAnfangszeit()));
			if (selectedCategory.getEndzeit() != null)
				tf_end.setText(sf.format(selectedCategory.getEndzeit()));
			chckbxNewCheckBox.setSelected(selectedCategory
					.getWochenendeErlaubt());
		}
	}
}
